<template>
    <popup
        :show="showEdit"
        :title="popTitle"
        :loading="loading"
        :async-close="true"
        width="500px"
        @close="emits('close')"
        @confirm="handleSubmit"
    >
        <div class="p-6 pb-0">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
                <el-form-item label="所属类目" prop="category_id">
                    <el-select
                        v-model="formData.category_id"
                        placeholder="请选择所属类目"
                        clearable
                    >
                        <el-option
                            v-for="(item, index) in categoryList"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item v-if="showMode === 'add'" label="词汇内容" prop="content">
                    <div class="w-full">
                        <el-input
                            type="textarea"
                            v-model="formData.content"
                            :autosize="{ minRows: 8, maxRows: 20 }"
                            placeholder="请输入关键词，如：超现实主义&Surrealism"
                        />
                        <div class="form-tips">
                            添加多个关键词，中英文以&隔开，按回车换行
                        </div>
                    </div>
                </el-form-item>
                <template v-else>
                    <el-form-item label="中文词汇" prop="prompt">
                        <el-input v-model="formData.prompt" placeholder="请输入关键词" maxlength="250" />
                    </el-form-item>
                    <el-form-item label="英文词汇" prop="prompt">
                        <el-input v-model="formData.prompt_en" placeholder="请输入关键词" maxlength="250" />
                    </el-form-item>
                </template>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="formData.sort" :min="0" :max="999999" />
                </el-form-item>
                <el-form-item label="状态" prop="is_show">
                    <el-radio-group v-model="formData.is_disable">
                        <el-radio :value="0">正常</el-radio>
                        <el-radio :value="1">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
        </div>
    </popup>
</template>

<script setup lang="ts">
import feedback from '@/utils/feedback'
import drawsPromptCategoryApi from '@/api/apply/draws/prompt_category'
import drawsPromptLexiconApi from '@/api/apply/draws/prompt_lexicon'

const emits = defineEmits(['success', 'close'])

const formRef = ref()
const showMode = ref<string>('add')
const showEdit = ref<boolean>(false)
const popTitle = computed<string>(() => {
    return showMode.value === 'edit' ? '编辑示例' : '新增示例'
})

// 分类列表
const categoryList = ref<any[]>([])

// 表单数据
const loading = ref(false)
const formData: any = reactive({
    id: '',          // ID
    engine: 'mj',    // 接口
    category_id: '', // 所属分类
    content: '',     // 词汇内容
    prompt: '',      // 中文词汇
    prompt_en: '',   // 英文词汇
    sort: 0,         // 排序编号
    is_disable: 0    // 是否禁用:[0=否, 1=是]
})

// 表单规则
const formRules: any = reactive({
    category_id: [
        { required: true, message: '请选择所属类目', trigger: ['blur'] }
    ],
    prompt: [
        { required: true, message: '中文词汇不能为空', trigger: ['blur'] },
        { max: 250, message: '中文词汇不能大于250个字符', trigger: ['blur'] }
    ],
    prompt_en: [
        { required: true, message: '英文词汇不能为空', trigger: ['blur'] },
        { max: 250, message: '英文词汇不能大于250个字符', trigger: ['blur'] }
    ],
    content: [
        { required: true, message: '词汇内容不能为空', trigger: ['blur'] }
    ]
})

/**
 * 提交表单
 */
const handleSubmit = async (): Promise<void> => {
    await formRef.value?.validate()
    loading.value = true
    if (showMode.value === 'edit') {
        await drawsPromptLexiconApi.edit(formData)
            .finally(() => {
                loading.value = false
            })
    } else {
        await drawsPromptLexiconApi.add(formData)
            .finally(() => {
                loading.value = false
            })
    }

    feedback.msgSuccess('操作成功')
    emits('close')
    emits('success')
}

/**
 * 打开表单
 *
 * @param {string} type
 * @param {any} row
 * @returns {Promise<void>}
 */
const open = async (type: string, row?: any): Promise<void> => {
    showMode.value = type
    showEdit.value = true

    if (type === 'edit') {
        for (const key in formData) {
            if (row[key] !== null && row[key] !== undefined) {
                formData[key] = row[key]
            }
        }
    }
}

defineExpose({
    open
})

onMounted(async () => {
    categoryList.value = await drawsPromptCategoryApi.lists({
        engine: 'mj'
    })
})
</script>
